package com.idp.web.generator.controller;

import java.io.File;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.idp.common.base.BaseController;
import com.idp.web.generator.entity.BuildCodeConfig;
import com.idp.web.generator.entity.CgColumnConfig;
import com.idp.web.generator.entity.CgDataSource;
import com.idp.web.generator.entity.CgTableConfig;
import com.idp.web.generator.service.CgDataSourceService;
import com.idp.web.generator.service.CgTableConfigService;
import com.idp.web.generator.util.CodeGenerateUtils;
import com.idp.web.generator.util.FieldUtils;
import com.idp.web.generator.util.ReadTableUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/generator")
public class GeneratorController extends BaseController {
	/*
	 * 日志
	 */
	private static Logger logger = Logger.getLogger(GeneratorController.class);
   
	@Resource
	private CgDataSourceService cgDataSourceService;
	@Resource
	private CgTableConfigService cgTableConfigService;

	/**
	 * 构建表格配置。
	 * @param session  用户session
	 * @param dataSourceId 数据元ID
	 * @param tableName  表名
	 * @param allTable   是否全部生成标识
	 * @return
	 */
	@RequestMapping("/buildConfig")
	@ResponseBody
	public String buildConfig(HttpSession session, Long dataSourceId,
			String tableName, String allTable) {
		JSONObject json = new JSONObject();
		@SuppressWarnings("unchecked")
		List<String> tables = (List<String>) session.getAttribute("tables");
		// 用户选择全选表
		if (allTable.equals("all") && tables.size() > 0) {
			int length = tables.size();
			for (int i = 0; i < length; i++) {
				CgTableConfig table = new CgTableConfig();
				table.setTableName(tables.get(i));
				table.setClassName(FieldUtils.formatFieldCapital(tables.get(i)));
				table.setIsCheckbox("N");
				table.setIsPage("Y");
				table.setIsTree("N");
				table.setCreateUser(getCurrentUser().getId());
				table.setCreateDate(new Date());
				CgDataSource dataSource = cgDataSourceService
						.getById(dataSourceId);
				table.setDatabaseName(dataSource.getDatabaseName());
				List<CgColumnConfig> columns;
				try {
					columns = new ReadTableUtils().readTableColumn(dataSource,
							tables.get(i));
					table.setColumns(columns);
					cgTableConfigService.add(table);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					json.put("result", "error");
					logger.error(e.getMessage(), e);
					return json.toString();
				}
			}
			json.put("result", "build_config_success");
			return json.toString();
		} else {

			try {

				CgTableConfig table = new CgTableConfig();
				table.setTableName(tableName);
				table.setClassName(FieldUtils.formatFieldCapital(tableName));
				table.setIsCheckbox("N");
				table.setIsPage("Y");
				table.setIsTree("N");
				table.setCreateUser(getCurrentUser().getId());
				table.setCreateDate(new Date());

				CgDataSource dataSource = cgDataSourceService
						.getById(dataSourceId);
				List<CgColumnConfig> columns = new ReadTableUtils()
						.readTableColumn(dataSource, tableName);
				table.setColumns(columns);
				cgTableConfigService.add(table);
				json.put("result", "build_config_success");
			} catch (Exception e) {
				json.put("result", "error");
				logger.error(e.getMessage(), e);
			}

			return json.toString();
		}
	}

	@RequestMapping("/goBuild")
	public String goBuild(Long id, HttpServletRequest request) {

		try {

			CgTableConfig tableConfig = cgTableConfigService.getById(id);
			request.setAttribute("tableConfig", tableConfig);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

		return "generator/table/buildCode";
	}

	@RequestMapping("/goAllBuild")
	public String goAllBuild(Long id, HttpServletRequest request) {

		try {

			// CgTableConfig tableConfig = cgTableConfigService.getById(id);
			// request.setAttribute("tableConfig", tableConfig);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

		return "generator/table/buildAllCode";
	}

	@RequestMapping("/buildCode")
	@ResponseBody
	public String buildCode(HttpSession session, BuildCodeConfig buildCodeConfig) {
		JSONObject json = new JSONObject();

		if (session.getAttribute("codeModel") == null) {
			json.put("result", "bulid_code_warn");

			return json.toString();
		}
		try {

			CgTableConfig tableConfig = cgTableConfigService
					.getById(buildCodeConfig.getTableId());
			buildCodeConfig.setTableConfig(tableConfig);
			// 生成代码
			CodeGenerateUtils generate = new CodeGenerateUtils(buildCodeConfig);
			generate.generateFile(session.getAttribute("codeModel").toString());

			json.put("result", "build_code_success");
		} catch (Exception e) {
			json.put("result", "error");
			logger.error(e.getMessage(), e);
		}

		return json.toString();
	}

	@SuppressWarnings("unchecked")
	@RequestMapping("/buildAllCode")
	@ResponseBody
	public String buildAllCode(HttpSession session,
			BuildCodeConfig buildCodeConfig) {
		JSONObject json = new JSONObject();
		if (session.getAttribute("codeModel") == null) {
			json.put("result", "bulid_code_warn");

			return json.toString();
		}
		try {

			List<CgTableConfig> list;
			if (session.getAttribute("tableList") == null) {
				list = cgTableConfigService.findAll();
			} else {
				list = (List<CgTableConfig>) session.getAttribute("tableList");
			}
			int length = list.size();
			for (int i = 0; i < length; i++) {
				CgTableConfig tableConfig = cgTableConfigService.getById(list
						.get(i).getId());
				buildCodeConfig.setTableConfig(tableConfig);
				// 生成代码
				CodeGenerateUtils generate = new CodeGenerateUtils(
						buildCodeConfig);
				generate.generateFile(session.getAttribute("codeModel")
						.toString());
				buildCodeConfig.setTableConfig(null);
				tableConfig = null;

			}

			json.put("result", "build_code_success");
		} catch (Exception e) {
			json.put("result", "error");
			logger.error(e.getMessage(), e);
		}

		return json.toString();
	}

	/**
	 * 返回子目录json
	 * 
	 * @param parentNode
	 * @return
	 */
	@RequestMapping("/doExpandFileTree")
	@ResponseBody
	public String doExpandFileTree(String parentNode) {
		JSONArray json = new JSONArray();

		try {

			if (StringUtils.isEmpty(parentNode)) {
				// 返回磁盘驱动器根目录
				File[] roots = File.listRoots();
				for (File r : roots) {

					JSONObject item = new JSONObject();
					item.put("id", r.getAbsolutePath());
					item.put("name", r.getPath());
					item.put("isParent", hasDirs(r));
					json.add(item);
				}
			} else {
				// 返回子目录集
				File parent = new File(parentNode);
				File[] chs = parent.listFiles();
				if (chs != null) {
					for (File r : chs) {
						JSONObject item = new JSONObject();
						if (r.isDirectory()) {
							item.put("id", r.getAbsolutePath());
							item.put("name", r.getName());
							item.put("isParent", hasDirs(r));
							json.add(item);
						} else {
							item.put("id", r.getAbsolutePath());
							item.put("name", r.getName());
							item.put("isParent", false);
							json.add(item);
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("该文件夹不可选择");
		}
		return json.toString();
	}

	private boolean hasDirs(File dir) {

		try {

			if (dir.listFiles().length == 0) {

				return false;
			} else {

				return true;
			}
		} catch (Exception e) {

			return false;
		}
	}
}
